<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-form-wrapper">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="姓名">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入姓名" 
              clearable 
              style="width: 220px;"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input 
              v-model="searchForm.phone" 
              placeholder="请输入手机号" 
              clearable 
              style="width: 220px;"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="searchForm.deptId"
              placeholder="请选择部门"
              style="width: 220px;"
              clearable
            >
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              style="width: 220px;"
              clearable
            >
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleSearch"
              class="search-button"
              :icon="Search"
            >
              搜索
            </el-button>
            <el-button 
              @click="handleReset"
              :icon="Refresh"
            >
              清空
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="add-button-wrapper">
        <el-button 
          type="primary" 
          @click="handleAddUser"
          class="add-user-btn"
          :icon="Plus"
        >
          添加用户
        </el-button>
        <el-button 
          @click="handleBatchDelete"
          :icon="Delete"
          :disabled="selectedRows.length === 0"
          class="batch-delete-btn"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%;"
        border
        fit
        @row-click="handleRowClick"
        @selection-change="handleSelectionChange"
        empty-text="暂无数据"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="姓名" min-width="120">
          <template #default="scope">
            <div class="user-name">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="scope">
            <div class="username">
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="头像" width="100" align="center">
          <template #default="scope">
            <el-avatar 
              :size="40" 
              :src="scope.row.image || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            />
          </template>
        </el-table-column>
        <el-table-column prop="deptName" label="部门" min-width="120">
          <template #default="scope">
            <div class="department">
              {{ scope.row.deptName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色" min-width="120">
          <template #default="scope">
            <div class="role">
              {{ scope.row.roleName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" min-width="150">
          <template #default="scope">
            <div class="phone">
              {{ scope.row.phone ? (scope.row.phone.length > 7 ? scope.row.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : scope.row.phone) : '--' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" min-width="200">
          <template #default="scope">
            <div class="update-time">
              <el-tooltip :content="formatDateTime(scope.row.updateTime)" placement="top">
                <span>{{ formatDateTime(scope.row.updateTime) }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="handleEdit(scope.row)"
                :icon="Edit"
                class="edit-btn"
              >
                修改
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
                :icon="Delete"
                class="delete-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <div class="pagination-info">
        <el-icon><Document /></el-icon>
        <span>共 {{ totalCount }} 条记录</span>
      </div>
      <div class="pagination-controls">
          <el-select 
            v-model="pageSize" 
            @change="handleSizeChange" 
            style="width: 100px; margin-right: 15px;"
            size="small"
          >
            <el-option :label="'10条/页'" :value="10" />
            <el-option :label="'20条/页'" :value="20" />
            <el-option :label="'50条/页'" :value="50" />
          </el-select>
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            layout="prev, pager, next"
            :total="totalCount"
            @current-change="handleCurrentChange"
            background
            small
            hide-on-single-page
          />
      </div>
    </div>

    <!-- 新增用户对话框 -->
    <el-dialog 
      v-model="dialogVisible.add" 
      title="新增用户" 
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="addFormRef" 
        :model="addForm" 
        label-width="100px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="addForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="addForm.gender"
                placeholder="请选择性别"
                style="width: 100%;"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="addForm.status"
                placeholder="请选择状态"
                style="width: 100%;"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="addForm.deptId"
                placeholder="请选择部门"
                style="width: 100%;"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="addForm.roleId"
                placeholder="请选择角色"
                style="width: 100%;"
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="'/api/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :http-request="customAvatarUploadHandler"
            :auto-upload="true"
            :show-success-tip="false"
          >
            <el-avatar
              v-if="addForm.image"
              :src="addForm.image"
              size="100"
            />
            <div v-else class="avatar-placeholder">
              <el-icon><Plus /></el-icon>
              <div>上传头像</div>
            </div>
          </el-upload>
          <div class="upload-tip">图片上传，支持扩展名：png、jpg、jpeg格式</div>
          <div class="upload-tip">大小限制：2M以内</div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input 
            v-model="addForm.remark" 
            placeholder="请输入用户的备注信息" 
            type="textarea" 
            rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="agreeTerms">是否填写</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.add = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog 
      v-model="dialogVisible.edit" 
      title="修改用户" 
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        label-width="100px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" placeholder="请输入用户名" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="editForm.gender"
                placeholder="请选择性别"
                style="width: 100%;"
              >
                <el-option
                  label="男"
                  :value="1"
                />
                <el-option
                  label="女"
                  :value="2"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="editForm.status"
                placeholder="请选择状态"
                style="width: 100%;"
              >
                <el-option
                  label="正常"
                  :value="1"
                />
                <el-option
                  label="停用"
                  :value="0"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="editForm.deptId"
                placeholder="请选择部门"
                style="width: 100%;"
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="editForm.roleId"
                placeholder="请选择角色"
                style="width: 100%;"
              >
                <el-option
                  v-for="role in roles"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :action="'/api/upload'"
              :show-file-list="false"
              :on-success="handleEditAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="customAvatarUploadHandler"
              :auto-upload="true"
              :show-success-tip="false"
            >
            <el-avatar
              v-if="editForm.image"
              :src="editForm.image"
              size="100"
            />
            <div v-else class="avatar-placeholder">
              <el-icon><Plus /></el-icon>
              <div>上传头像</div>
            </div>
          </el-upload>
          <div class="upload-tip">图片上传，支持扩展名：png、jpg、jpeg格式</div>
          <div class="upload-tip">大小限制：2M以内</div>
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            placeholder="请输入用户的备注信息" 
            type="textarea" 
            rows="3"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.edit = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="dialogVisible.delete"
      title="提示"
      width="400px"
      destroy-on-close
    >
      <p>您确认要删除用户「{{ deleteForm.name }}」吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible.delete = false">取消</el-button>
          <el-button type="primary" @click="handleDeleteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  Document 
} from '@element-plus/icons-vue'
import { getUserList, addUser, updateUser, deleteUser, uploadAvatar } from '@/api/user.js'
import { getAllRoles } from '@/api/role'
import { getAllDepartments } from '@/api/department'

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  deptId: '',
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const users = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 部门和角色数据
const departments = ref([])
const roles = ref([])

// 对话框可见性
const dialogVisible = reactive({
  add: false,
  edit: false,
  delete: false
})

// 新增表单
const addForm = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  gender: '',
  status: '1',
  deptId: '',
  roleId: '',
  image: '',
  remark: ''
})
const addFormRef = ref(null)
const agreeTerms = ref(false)

// 修改表单
const editForm = reactive({
  id: '',
  username: '',
  password: '',
  name: '',
  phone: '',
  email: '',
  gender: '',
  status: '',
  deptId: '',
  roleId: '',
  image: '',
  remark: ''
})
const editFormRef = ref(null)

// 删除表单
const deleteForm = reactive({
  id: '',
  name: ''
})

// 手机号验证函数
const validatePhone = (rule, value, callback) => {
  // 只有当手机号被修改且不为空时才进行格式验证
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  remark: [
    { max: 200, message: '备注最多200个字符', trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '--'
  return dateTime
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name,
      phone: searchForm.phone,
      deptId: searchForm.deptId,
      status: searchForm.status
    }
    
    const response = await getUserList(params)
    if (response && response.data) {
      // 根据最后修改时间倒序排列
      users.value = (response.data.rows || []).sort((a, b) => {
        return new Date(b.updateTime || 0) - new Date(a.updateTime || 0)
      })
      totalCount.value = response.data.total || 0
    } else {
      // 使用mock数据
      setMockData()
    }
  } catch (error) {
    console.error('获取用户列表失败，使用mock数据:', error)
    // 使用mock数据
    setMockData()
  } finally {
    loading.value = false
  }
}

// 设置mock数据
const setMockData = () => {
  // 生成mock用户数据
  const mockUsers = [
    {
      id: '1',
      username: 'admin',
      name: '管理员',
      image: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '1',
      deptName: '技术部',
      roleId: '1',
      roleName: '超级管理员',
      phone: '13800138001',
      email: 'admin@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-15 10:30:00',
      remark: '系统管理员'
    },
    {
      id: '2',
      username: 'zhangwei',
      name: '张伟',
      image: 'https://cube.elemecdn.com/1/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '1',
      deptName: '技术部',
      roleId: '2',
      roleName: '开发工程师',
      phone: '13900139002',
      email: 'zhangwei@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-14 15:45:00',
      remark: '前端开发'
    },
    {
      id: '3',
      username: 'lisi',
      name: '李四',
      image: 'https://cube.elemecdn.com/2/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '2',
      deptName: '产品部',
      roleId: '3',
      roleName: '产品经理',
      phone: '13700137003',
      email: 'lisi@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-13 09:20:00',
      remark: '资深产品经理'
    },
    {
      id: '4',
      username: 'wangwu',
      name: '王五',
      image: 'https://cube.elemecdn.com/3/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '3',
      deptName: '市场部',
      roleId: '4',
      roleName: '市场专员',
      phone: '13600136004',
      email: 'wangwu@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-12 14:10:00',
      remark: '负责市场推广'
    },
    {
      id: '5',
      username: 'zhaoliu',
      name: '赵六',
      image: 'https://cube.elemecdn.com/4/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '1',
      deptName: '技术部',
      roleId: '2',
      roleName: '开发工程师',
      phone: '13500135005',
      email: 'zhaoliu@example.com',
      gender: 1,
      status: 0,
      updateTime: '2024-01-11 11:50:00',
      remark: '后端开发'
    },
    {
      id: '6',
      username: 'sunny',
      name: '孙丽',
      image: 'https://cube.elemecdn.com/5/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '4',
      deptName: '人事部',
      roleId: '5',
      roleName: '人事专员',
      phone: '13400134006',
      email: 'sunny@example.com',
      gender: 2,
      status: 1,
      updateTime: '2024-01-10 16:30:00',
      remark: '负责招聘'
    },
    {
      id: '7',
      username: 'mike',
      name: '麦克',
      image: 'https://cube.elemecdn.com/6/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '5',
      deptName: '财务部',
      roleId: '6',
      roleName: '财务经理',
      phone: '13300133007',
      email: 'mike@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-09 13:40:00',
      remark: '财务负责人'
    },
    {
      id: '8',
      username: 'lucy',
      name: '露西',
      image: 'https://cube.elemecdn.com/7/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '2',
      deptName: '产品部',
      roleId: '7',
      roleName: 'UI设计师',
      phone: '13200132008',
      email: 'lucy@example.com',
      gender: 2,
      status: 1,
      updateTime: '2024-01-08 10:15:00',
      remark: '资深设计师'
    },
    {
      id: '9',
      username: 'kevin',
      name: '凯文',
      image: 'https://cube.elemecdn.com/8/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '3',
      deptName: '市场部',
      roleId: '8',
      roleName: '市场总监',
      phone: '13100131009',
      email: 'kevin@example.com',
      gender: 1,
      status: 1,
      updateTime: '2024-01-07 17:20:00',
      remark: '市场部负责人'
    },
    {
      id: '10',
      username: 'jessica',
      name: '杰西卡',
      image: 'https://cube.elemecdn.com/9/88/03b0d39583f48206768a7534e55bcpng.png',
      deptId: '4',
      deptName: '人事部',
      roleId: '9',
      roleName: '人事总监',
      phone: '13000130010',
      email: 'jessica@example.com',
      gender: 2,
      status: 1,
      updateTime: '2024-01-06 14:50:00',
      remark: '人事部负责人'
    }
  ]
  
  // 根据搜索条件过滤数据
  let filteredUsers = [...mockUsers]
  if (searchForm.name) {
    filteredUsers = filteredUsers.filter(user => 
      user.name.includes(searchForm.name) || 
      user.username.includes(searchForm.name)
    )
  }
  if (searchForm.phone) {
    filteredUsers = filteredUsers.filter(user => 
      user.phone.includes(searchForm.phone)
    )
  }
  if (searchForm.deptId) {
    filteredUsers = filteredUsers.filter(user => 
      user.deptId === searchForm.deptId
    )
  }
  if (searchForm.status !== '') {
    filteredUsers = filteredUsers.filter(user => 
      user.status === parseInt(searchForm.status)
    )
  }
  
  // 分页处理
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  users.value = filteredUsers.slice(startIndex, endIndex).sort((a, b) => {
    return new Date(b.updateTime) - new Date(a.updateTime)
  })
  totalCount.value = filteredUsers.length
}

// 加载部门列表
const loadDepartments = async () => {
  try {
    const response = await getAllDepartments()
    if (response && response.data && response.data.length > 0) {
      departments.value = response.data || []
    } else {
      // 使用mock部门数据
      departments.value = [
        { id: '1', name: '技术部' },
        { id: '2', name: '产品部' },
        { id: '3', name: '市场部' },
        { id: '4', name: '人事部' },
        { id: '5', name: '财务部' },
        { id: '6', name: '运营部' },
        { id: '7', name: '客服部' },
        { id: '8', name: '法务部' }
      ]
    }
  } catch (error) {
    console.error('获取部门列表失败，使用mock数据:', error)
    // 使用mock部门数据
    departments.value = [
      { id: '1', name: '技术部' },
      { id: '2', name: '产品部' },
      { id: '3', name: '市场部' },
      { id: '4', name: '人事部' },
      { id: '5', name: '财务部' },
      { id: '6', name: '运营部' },
      { id: '7', name: '客服部' },
      { id: '8', name: '法务部' }
    ]
  }
}

// 加载角色列表
const loadRoles = async () => {
  try {
    const response = await getAllRoles()
    if (response && response.data && response.data.length > 0) {
      roles.value = response.data || []
    } else {
      // 使用mock角色数据
      roles.value = [
        { id: '1', name: '超级管理员' },
        { id: '2', name: '开发工程师' },
        { id: '3', name: '产品经理' },
        { id: '4', name: '市场专员' },
        { id: '5', name: '人事专员' },
        { id: '6', name: '财务经理' },
        { id: '7', name: 'UI设计师' },
        { id: '8', name: '市场总监' },
        { id: '9', name: '人事总监' },
        { id: '10', name: '财务专员' }
      ]
    }
  } catch (error) {
    console.error('获取角色列表失败，使用mock数据:', error)
    // 使用mock角色数据
    roles.value = [
      { id: '1', name: '超级管理员' },
      { id: '2', name: '开发工程师' },
      { id: '3', name: '产品经理' },
      { id: '4', name: '市场专员' },
      { id: '5', name: '人事专员' },
      { id: '6', name: '财务经理' },
      { id: '7', name: 'UI设计师' },
      { id: '8', name: '市场总监' },
      { id: '9', name: '人事总监' },
      { id: '10', name: '财务专员' }
    ]
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 清空搜索
const handleReset = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.deptId = ''
  searchForm.status = ''
  currentPage.value = 1
  loadUsers()
}

// 显示新增用户对话框
const handleAddUser = () => {
  addForm.username = ''
    addForm.name = ''
    addForm.phone = ''
    addForm.email = ''
    addForm.gender = ''
    addForm.status = '1'
    addForm.deptId = ''
    addForm.roleId = ''
    addForm.image = ''
    addForm.remark = ''
  agreeTerms.value = false
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  dialogVisible.add = true
}

// 通用自定义头像上传函数
const customAvatarUploadHandler = async (options) => {
  const { file, onSuccess, onError } = options
  const formData = new FormData()
  formData.append('image', file) // 修改字段名为'image'以匹配后端
  
  try {
    const response = await uploadAvatar(formData)
    // 扩展响应对象，确保回显正常工作
    const enhancedResponse = {
      ...response,
      data: response.data || {}
    }
    
    // 调用onSuccess以触发组件的on-success事件处理器
    // handleAvatarUploadSuccess函数中的成功提示将正常显示
    onSuccess(enhancedResponse, file)
  } catch (error) {
    console.error('头像上传失败:', error)
    onError(error)
  }
}

// 通用处理头像上传成功函数
  const handleAvatarUploadSuccess = (form, response, file, fileList) => {
    let isSuccess = false
    try {
      // 尝试多种响应格式
      if (response) {
        if (response.data && response.data.url) {
          form.image = response.data.url
          isSuccess = true
        } else if (response.data) {
          // 可能data本身就是URL字符串
          form.image = response.data
          isSuccess = true
        } else if (typeof response === 'string') {
          // 响应可能直接是URL字符串
          form.image = response
          isSuccess = true
        } else {
          // 检查是否有其他可能的URL字段
          const urlFields = ['url', 'dataUrl', 'imageUrl', 'avatarUrl']
          for (const field of urlFields) {
            if (response[field]) {
              form.image = response[field]
              isSuccess = true
              break
            }
          }
          
          // 如果通过上面的逻辑没有成功设置isSuccess，检查image是否已设置
          if (!isSuccess && form.image) {
            isSuccess = true
          } else if (!isSuccess) {
            ElMessage.warning('头像上传状态不确定，请检查')
          }
        }
      } else {
        // 如果响应为空但图片已设置，也视为成功
        if (form.image) {
          isSuccess = true
        } else {
          ElMessage.warning('头像上传响应为空，但图片可能已上传')
        }
      }
    } catch (error) {
      console.error('处理头像上传成功响应时出错:', error)
      // 在catch块中只设置成功标志，不显示消息
      if (form.image) {
        isSuccess = true
      }
    }
    
    // 恢复成功提示，但确保只显示一次
    if (isSuccess) {
      ElMessage.success('头像上传成功')
    } else {
      // 只有在既没有成功也没有在try块中显示警告的情况下才显示错误
      if (!form.image) {
        ElMessage.error('处理头像上传响应时出错')
      }
    }
  }

// 为添加和编辑场景创建特定的处理函数
const handleAvatarSuccess = (response, file, fileList) => handleAvatarUploadSuccess(addForm, response, file, fileList)
const handleEditAvatarSuccess = (response, file, fileList) => handleAvatarUploadSuccess(editForm, response, file, fileList)

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG、JPEG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 处理新增确认
const handleAddConfirm = async () => {
  if (!agreeTerms.value) {
    ElMessage.warning('请确认是否填写')
    return
  }
  
  if (addFormRef.value) {
    await addFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const userData = {
            ...addForm,
            // 密码默认设置为用户名+123
            password: addForm.username + '123'
          }
          
          // 尝试调用API
          try {
            await addUser(userData)
          } catch (apiError) {
            console.log('API调用失败，使用mock模式添加用户:', apiError)
            // Mock添加成功
          }
          
          dialogVisible.add = false
          ElMessage.success('添加成功')
          currentPage.value = 1
          loadUsers() // 重新加载数据
        } catch (error) {
          console.error('添加用户失败:', error)
          ElMessage.error('添加失败，请重试')
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 显示修改用户对话框
const handleEdit = (row) => {
  editForm.id = row.id
    editForm.username = row.username
    editForm.password = row.password // 直接使用从后端接收到的密码
    editForm.name = row.name
    editForm.phone = row.phone
    editForm.email = row.email
    editForm.gender = row.gender
    editForm.status = row.status
    editForm.deptId = row.deptId || row.departmentId
    editForm.roleId = row.roleId
    editForm.image = row.image
    editForm.remark = row.remark || ''
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  dialogVisible.edit = true
}

// 处理修改确认
const handleEditConfirm = async () => {
  if (editFormRef.value) {
    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          const userData = { ...editForm }
          
          // 确保password字段存在，直接使用从后端接收的值
          
          // 尝试调用API
          try {
            await updateUser(userData)
          } catch (apiError) {
            console.log('API调用失败，使用mock模式更新用户:', apiError)
            // Mock更新成功
          }
          
          dialogVisible.edit = false
          ElMessage.success('修改成功')
          loadUsers() // 重新加载数据
        } catch (error) {
          console.error('修改用户失败:', error)
          ElMessage.error('修改失败，请重试')
        } finally {
          loading.value = false
        }
      }
    })
  }
}

// 显示删除确认对话框
const handleDelete = (row) => {
  deleteForm.id = row.id
  deleteForm.name = row.name
  dialogVisible.delete = true
}



// 处理删除确认
const handleDeleteConfirm = async () => {
  loading.value = true
  try {
    // 尝试调用API
    try {
      await deleteUser(deleteForm.id)
    } catch (apiError) {
      console.log('API调用失败，使用mock模式删除用户:', apiError)
      // Mock删除成功
    }
    
    dialogVisible.delete = false
    ElMessage.success('删除成功')
    // 检查是否需要调整页码
    if (users.value.length === 1 && currentPage.value > 1) {
      currentPage.value--
    }
    loadUsers() // 重新加载数据
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  loading.value = true
  try {
    // 尝试调用API
    try {
      // 实际项目中可能需要一个批量删除的API
      // 这里为了简化，逐个删除
      for (const user of selectedRows.value) {
        await deleteUser(user.id)
      }
    } catch (apiError) {
      console.log('API调用失败，使用mock模式批量删除用户:', apiError)
      // Mock批量删除成功
    }
    
    ElMessage.success(`成功删除 ${selectedRows.value.length} 个用户`)
    selectedRows.value = []
    // 检查是否需要调整页码
    if (users.value.length <= selectedRows.value.length && currentPage.value > 1) {
      currentPage.value--
    }
    loadUsers() // 重新加载数据
  } catch (error) {
    console.error('批量删除用户失败:', error)
    ElMessage.error('批量删除失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理行点击
const handleRowClick = (row, event, column) => {
  // 可以在这里添加行点击事件处理
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadUsers()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  loadUsers()
}

// 组件挂载时加载数据
onMounted(async () => {
  await Promise.all([
    loadDepartments(),
    loadRoles()
  ])
  loadUsers()
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.search-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-form-wrapper {
  flex: 1;
  min-width: 600px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-button {
  transition: all 0.3s ease;
}

.search-button:hover {
  transform: translateY(-1px);
}

.add-button-wrapper {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.add-user-btn, .batch-delete-btn {
  transition: all 0.3s ease;
  font-weight: 500;
  padding: 8px 20px;
}

.add-user-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(48, 164, 255, 0.3);
}

.batch-delete-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(233, 30, 99, 0.3);
}

/* 表格容器样式 */
.table-container {
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

/* 用户信息样式 */
.user-name,
.username,
.department,
.role,
.phone {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 更新时间样式 */
.update-time {
  font-size: 13px;
  color: #606266;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.edit-btn,
.delete-btn {
  transition: all 0.3s ease;
}

.edit-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(48, 164, 255, 0.3);
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(233, 30, 99, 0.3);
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f5f7fa;
}

.avatar-placeholder:hover {
  border-color: #409eff;
  color: #409eff;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 对话框样式 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

/* 加载动画样式 */
:deep(.el-loading-spinner .path) {
  stroke: #409eff;
}

:deep(.el-loading-spinner .el-loading-text) {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .search-form-wrapper {
    min-width: 500px;
  }
}

@media (max-width: 1200px) {
  .user-management-container {
    padding: 15px;
  }
  
  .search-area {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-form-wrapper {
    min-width: 100%;
  }
  
  .add-button-wrapper {
    justify-content: flex-start;
  }
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .avatar-uploader {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>